package com.csust.cg.mongodb.contorller;

import com.csust.cg.mongodb.domain.HttpStatus;
import com.csust.cg.mongodb.domain.Result;
import com.csust.cg.mongodb.domain.entity.User;
import com.csust.cg.mongodb.domain.vo.UserVO;
import com.csust.cg.mongodb.service.UserService;
import com.csust.cg.mongodb.utils.CodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenguang
 */
@RestController
@RequestMapping("/api/user")
@ResponseBody
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/getCode")
    public void getCode(@RequestParam(name = "codeLength", required = false, defaultValue = "4") Integer codeLength,
                        @RequestParam(name = "w", required = false, defaultValue = "100") Integer width,
                        @RequestParam(name = "h", required = false, defaultValue = "30") Integer height,
                        @RequestParam(name = "codeType", defaultValue = "code") String codeType,
                        HttpServletRequest request,
                        HttpServletResponse response) {
        CodeUtils codeUtils = new CodeUtils(codeLength, width, height);
        String generatorCode = codeUtils.generatorCode();
        request.getSession().setAttribute(codeType, generatorCode);
        BufferedImage generatorRotateCodeImage = codeUtils.generatorRotateCodeImage(generatorCode, true);
        try {
            ImageIO.write(generatorRotateCodeImage, "gif", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/login")
    public Result login(@Validated UserVO user, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object code = session.getAttribute("code");
        if (code == null || !user.getCode().equalsIgnoreCase(code.toString())) {
            return new Result("验证码错误！", HttpStatus.CODE_ERROR);
        }
        User findUser;
        try {
            findUser = userService.checkUser(user.getUsername(), user.getPassword());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统错误，请联系开发人员！");
        }
        if (findUser == null) {
            return new Result("用户不存在", HttpStatus.USER_NOT_FOUND);
        }
        session.setAttribute("token", findUser.getId());
        Map<String, Object> result = new HashMap<>(2);
        result.put("token", findUser.getId());
        result.put("username", findUser.getUsername());
        return Result.success(null, result);
    }

    @PostMapping("/register")
    public Result register(@Validated UserVO user, HttpServletRequest request) {
        Object code = request.getSession().getAttribute("code");
        if (code == null || !user.getCode().equalsIgnoreCase(code.toString())) {
            return new Result("验证码错误！", HttpStatus.CODE_ERROR);
        }
        return userService.createUser(user.getUsername(), user.getPassword());
    }

    @GetMapping("/logout")
    public Result logout(HttpServletRequest request) {
        request.getSession().removeAttribute("token");
        return Result.success();
    }
}
